package com.study.rabbitmq.workQueue;

import com.rabbitmq.client.CancelCallback;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.DeliverCallback;
import com.rabbitmq.client.Delivery;
import com.study.rabbitmq.utils.RabbitMqUtil;

import java.io.IOException;

public class Consume {

    private static final String QUEUE_NAME = "queue";

    public static void main(String[] args) throws IOException {
        Channel channel = RabbitMqUtil.getChannel();
        DeliverCallback deliverCallback = new DeliverCallback() {
            @Override
            public void handle(String consumerTag, Delivery message) throws IOException {
                sleep(2);
                System.out.print("接收到的消息：");
                System.out.println(new String(message.getBody()));
                //休眠十秒种
                //处理完消息进行应答  1.获取消息的标记tag 2.false 代表只应答接收到的那个消息 true代表应答所在信道中的所有消息
                channel.basicAck(message.getEnvelope().getDeliveryTag(),false);
            }
        };
        CancelCallback cancelCallback = new CancelCallback() {
            @Override
            public void handle(String consumerTag) throws IOException {
                System.out.println("中断消息接收！");
            }
        };

        //设置消息的分发方式， 0：轮询分发  1：不公平分发（能者多劳） 大于1就是预取值
        channel.basicQos(2);

        //消息手动应答
        channel.basicConsume(QUEUE_NAME,false,deliverCallback,cancelCallback);
        System.out.println("消息队列C2干活能力弱.。。。");
    }

    public static void sleep(Integer second) {
        try {
            Thread.sleep(second*1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }
}
